package com.gxa.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.R;
import com.gxa.service.UserService;
import com.gxa.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    创建响应实体类对象
        R r = new R();
//        获取输入的验证码
        String vercode = request.getParameter("vercode");
//        获取生成的验证码
        String code = request.getSession().getAttribute("serverCode").toString();
//        创建service对象
        UserService userService = new UserServiceImpl();
//        校验验证码是否正确
        if(code.equalsIgnoreCase(vercode)){//忽略大小写比较
            //验证码正确
            //获取用户名、密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //调用service
            r = userService.login(username, password);
        }else{
            r.setCode(401);
            r.setMsg("验证码错误");
        }
        //响应数据R
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(r));
    }
}
